package com.example.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSON;
import com.example.common.Result;
import com.example.pojo.entity.Team;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Base64;

/**
 * TODO
 *
 * @author ding
 * @since 2024/6/24
 */
public class QRCodeUtils {
    public void createQRCode() {
        QrConfig config = new QrConfig();

        Team team = Team.builder()
                .name("东方幻想乡")
                .description("欢迎来到东方幻想乡")
                .num(10)
                .build();

        Object json = JSON.toJSON(team);
        String string = json.toString();
        System.out.println(string);

        // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
        // 设置前景色，既二维码颜色（青色）  设置之后无法解析二维码
//        config.setForeColor(Color.CYAN.getRGB());
        // 设置背景色（灰色）
        config.setBackColor(Color.GRAY.getRGB());

        QrCodeUtil.generate(string, config, FileUtil.file("E:\\picture\\engine\\" + team.getName() + ".jpg"));
    }

    public void createQRCode2() throws WriterException, IOException {
        //需要编码的内容
        String urlCode = "这是我生成的二维码";
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //设置二维码图片宽高
        BitMatrix bitMatrix1 = qrCodeWriter.encode(urlCode, BarcodeFormat.QR_CODE,600,600);
        //输出到指定路径
        Path path = FileSystems.getDefault().getPath("E:/picture/engine/MyQRCode.png");
        MatrixToImageWriter.writeToPath(bitMatrix1,"PNG",path);
        // 写到输出流
        ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix1, "PNG", outputStream1);
        //转换为base64
        Base64.Encoder encoder1 = Base64.getEncoder();
        String advUrl = "data:image/jpeg;base64,"
                +encoder1.encodeToString(outputStream1.toByteArray());
        //打印base64结果
        System.out.println(advUrl);

    }

    /**
     * 解析二维码
     */
    public Result decodeQRCode(){
        String decode = QrCodeUtil.decode(FileUtil.file("E:\\picture\\engine\\东方幻想乡.jpg"));
        System.out.println("二维码解析的内容为:" + decode);
        Object parse = JSON.parse(decode);
        return Result.success(parse);
    }



}
